# third party
import sys
import time
import random
import socket
import string
import threading

try:
	import cPickle as pickle
except:
	import pickle

# first party
from torrent import Torrent
from appWindow import AppWindow
from throttle import Throttle



class Client:
	def __init__ (self):
		self.torrents = []
		self.alive = True


		# prep some support stuff
		self.sendThrottle = Throttle()
		self.recvThrottle = Throttle()
		self.saveLock = threading.Lock()

		

		# prep the in-socket
		self.localPort = 0
		self.localSock = socket.socket()

		while self.localPort == 0:
			try:
				self.localPort = random.randint(49152, 65535)
				self.localSock.bind(("", self.localPort))
			except socket.error as err:
				self.localPort = 0

		

		# load any saved data that might exist
		try:
			localDataFile = open("local.data", "rb")
			self.localData = pickle.load( localDataFile )
			localDataFile.close()
		except:
			self.localData = {}

		if (not "id" in self.localData) or len(self.localData["id"]) != 20:
			self.localData["id"] = "Barebones.00-" + str(random.randint(0,9999999)).zfill(7)

		if not "savedTorrents" in self.localData:
			self.localData["savedTorrents"] = {}

		# load up the saved torrents
		for torrentGUID in self.localData["savedTorrents"]:
			torrent = Torrent( self )
			torrent.initFromSavedData( self.localData["savedTorrents"][torrentGUID] )
			torrent.contactTracker("started")
			self.torrents.append( torrent )

		
		self.periodicSaveThread = threading.Thread(target=self.saveDataTimeout)
		self.periodicSaveThread.start()

			
	def getTorrent (self, torrentGUID):
		for torrent in self.torrents:
			if torrent.GUID == torrentGUID:
				return torrent
		return None


	def addTorrentFromFile (self, filename):
		torrent = Torrent( self, filename )
		if not torrent.GUID in self.localData["savedTorrents"]:
			torrent.contactTracker("started")
			self.torrents.append( torrent )
			self.saveData()
			return torrent
		return None


	def saveData (self):
		with self.saveLock:
			for torrent in self.torrents:
				self.localData["savedTorrents"][torrent.GUID] = torrent.getSaveData()

			localDataFile = open("local.data", "wb")
			pickle.dump( self.localData, localDataFile )
			localDataFile.close()

	def saveDataTimeout (self):
		while self.alive:
			self.saveData()
			time.sleep(560)

		

	def kill (self):
		self.alive = False
		self.saveData()
		for torrent in self.torrents:
			torrent.kill()
		self.sendThrottle.kill()
		self.recvThrottle.kill()
		sys.exit()

# get this party started
AppWindow( Client() )



